//
//  WDHTTPMethod.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2017/1/16.
//  Copyright © 2017年 王笛. All rights reserved.
//

#import "WDHTTPMethod.h"
#import "WDChangeString.h"
#import "MJExtension.h"
@implementation WDHTTPMethod

+(void)getDataByString:(NSString *)urlString BODYDic:(NSDictionary *)bodyDic WithDataBlock:(void (^)(id))dataBlock{
    //1.字符串转码
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlString]];
    //2.创建管理者对象(session)
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //请求超时时间
    manager.requestSerializer.timeoutInterval = 10.0;
    
    //3.设置允许请求的类别
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js", @"application/x-javascript", nil];
    //4.开始请求
    if (!bodyDic) {
        
        //GET;
        [manager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            dataBlock(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            //WDLog(@"%@", error);
            
        }];
        
    } else {
        //POST;
        [manager POST:urlString parameters:bodyDic constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            dataBlock(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documents = [array lastObject];
            NSString *documentPath = [documents stringByAppendingPathComponent:@"saveArray.plist"];
            NSDictionary *resultDic = [NSDictionary dictionaryWithContentsOfFile:documentPath];
            dataBlock(resultDic);
            
        }];
    }
}

+(void)postUpLoadDataByString:(NSString *)urlString BODYDic:(NSDictionary *)bodyDic ImageData_1:(NSData *)data1 ImageName_1:(NSString *)string1 WithDataBlock:(void (^)(id))dataBlock
{
    //1.字符串转码
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlString]];
    
    //2.创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //3.设置允许请求的类别
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js", @"application/x-javascript", nil];
    
    // 2.发送一个请求
    [manager POST:urlString parameters:bodyDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        
        //上传头像
        [formData appendPartWithFileData:data1 name:string1 fileName:fileName mimeType:@"image/png"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"121图片上传:%@",responseObject);
        //WDLog(@"上传成功");
        dataBlock(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"faerror:%@",error);
        //WDLog(@"上传失败");
        
    }];
}

+ (void)postUpLoadDuoTuDataByString:(NSString *)urlString BODYDic:(NSDictionary *)bodyDic imagesData:(NSArray<NSData *> *)imagesData WithDataBlock:(void (^)(id))dataBlock
{
    //1.字符串转码
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlString]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js", @"application/x-javascript", nil];
    
    [manager POST:urlString parameters:bodyDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //多图上传
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //WDLog(@"上传成功");
        dataBlock(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        WDLog(@"上传失败");
        
    }];
}

+ (void)xy_requestPostJsonWithUrl:(NSString *)url withItemClass:(Class)itemClass parameters:(id)parameters isAddCookie:(BOOL)isAdd success:(void(^)(id responseObject))success fail:(void(^)())fail{
    
    if(isAdd){
        NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:WDURLLogin];
        if([cookiesdata length]) {
            NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
            NSHTTPCookie *cookie;
            for (cookie in cookies) {
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            }
        }

    }
    
    NSMutableDictionary * paraMDic = [NSMutableDictionary dictionaryWithDictionary:parameters];
    
    [paraMDic setObject:@"3" forKey:@"ctime"];
    
    NSLog(@"\n请求url:%@\n\n参数:%@\n",url,parameters);
    AFHTTPSessionManager * xyManager = [AFHTTPSessionManager manager];
    xyManager.responseSerializer = [AFJSONResponseSerializer serializer];
    xyManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    xyManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
    [xyManager POST:url parameters:paraMDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if(success){
            NSLog(@"结果:%@",responseObject);
            if(itemClass == nil){
                success(responseObject);
            }else{
                success( [itemClass mj_objectWithKeyValues:responseObject]);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(fail){
            fail(error);
            
        }
    }];
    
    
    
    
    
}

+ (void)xy_requestPostUploadWithUrl:(NSString *)url withItemClass:(Class)itemClass withImgData:(NSData *)imgData withName:(NSString *)name withParameters:(id)parameters success:(void(^)(id responseObject))success fail:(void(^)())fail{
    
    NSLog(@"\n请求url:%@\n\n参数:%@\n",url,parameters);

     NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:WDURLLogin];
    if([cookiesdata length]) {
            NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
            NSHTTPCookie *cookie;
            for (cookie in cookies) {
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            }
        }
    
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
//    manager.responseSerializer = [[AFCompoundResponseSerializer alloc] init];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Conent-Type"];
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:imgData name:name fileName:[NSString stringWithFormat:@"%@.png",@"123321"] mimeType:@"image/png"];
        //[formData appendPartWithFileData:UIImageJPEGRepresentation(avatars,1) name:@"avatar" fileName:@"avatar.png" mimeType:@"image/png"];
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if(success){
            NSLog(@"结果:%@",responseObject);

            if(itemClass == nil){
                success(responseObject);
            }else{
                success([itemClass mj_objectWithKeyValues:responseObject]);
            }
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"结果:%@",error);

        if(fail)
        {
            fail();
        }
    }];
    
}

@end







